#include "threadPool.h"
int client_id[CLIENT_NUM];
int exitpipe[2];
void sigFunc(int sigNum){
    printf("signum = %d\n",sigNum);
    write(exitpipe[1],"1",1);
    printf("parent got signal\n");
}

int main(int argc, char *argv[]){
    // ./server workernum
    ARGS_CHECK(argc, 2);
    //创建argv[1]个子线程
    int workerNum = atoi(argv[1]);
    pipe(exitpipe);
    if(fork() != 0){
        close(exitpipe[0]);
        signal(SIGUSR1,sigFunc);
        wait(NULL);
        exit(0);
    }
    close(exitpipe[1]);
    //初始化线程池（包括任务队列）
    threadPool_t threadPool;
    threadPoolInit(&threadPool,workerNum);
    //创建若干个子线程
    makeWorker(&threadPool);
    //初始化tcp连接
    int sockfd;
    tcpInit("./config/server_1.conf",&sockfd);
    //创建用于接收命令与传递信息的结构体
    cmd_t Cmd;
    //初始化用于存储客户user_id的数组
    memset(client_id,-1,sizeof(client_id));
    // 初始化本地文件表（用于秒传）
    init_local_file();
    //建立epoll监听
    int epfd = epollCtor();
    epollAdd(epfd,sockfd);
    epollAdd(epfd,exitpipe[0]);
    struct epoll_event readyset[2];
    while(1){
        int readynum = epoll_wait(epfd,readyset,2,-1);
        for(int i = 0 ; i < readynum ; i++){
            if(sockfd == readyset[i].data.fd){//监听到建立连接请求
                int netfd = accept(sockfd,NULL,NULL);
                epollAdd(epfd,netfd);
                printf("connection established!\n");
            }
            else if(exitpipe[0] == readyset[i].data.fd){//监听到退出信号
                remove_local_file();
                printf("threadpool exit!\n");
                pthread_mutex_lock(&threadPool.taskQueue.mutex);
                threadPool.isexit = 1;
                pthread_mutex_unlock(&threadPool.taskQueue.mutex);
                pthread_cond_broadcast(&threadPool.taskQueue.cond);
                for(int i = 0 ; i < workerNum ; ++i){
                    pthread_join(threadPool.tidArr[i], NULL);
                }   
                puts("done");
                exit(0);
            }
            else{// 监听到客户端的消息
                int netfd = readyset[i].data.fd;
                //printf("netfd = %d\n", netfd);
                bzero(&Cmd,sizeof(cmd_t));
                int ret = recv(netfd,&Cmd,sizeof(cmd_t),0);
                if(Cmd.token == -1 || ret == 0){
                    printf("NO.%d client is exit!\n",client_id[netfd]);
                    update_user_path(client_id[netfd],"~/",0);
                    client_id[netfd] = -1;
                    epollDel(epfd,netfd);
                    close(netfd);
                    continue;
                }
                SYS_LOG_INFO(Cmd);
                pthread_mutex_lock(&threadPool.taskQueue.mutex);
                taskEnQueue(&threadPool.taskQueue,Cmd,netfd);
                pthread_cond_signal(&threadPool.taskQueue.cond);
                printf("main sent a new task!\n");
                pthread_mutex_unlock(&threadPool.taskQueue.mutex);
            }
        }
    } 
}